package com.example.reactordemo.handler;

import com.example.reactordemo.model.User;
import com.example.reactordemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import static org.springframework.http.MediaType.APPLICATION_JSON;

/**
 * 用户操作类
 */
@Component
public class UserHandler {

    @Autowired
    private UserRepository userRepository;

    /**
     * 根据Id查询用户信息
     * @param request
     * @return
     */
    public Mono<ServerResponse> findUserById(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        return ServerResponse.ok().contentType(APPLICATION_JSON).body(userRepository.findById(id),User.class);
    }

    /**
     * 查找全部用户信息
     * @param request
     * @return
     */
    public Mono<ServerResponse> findUsers(ServerRequest request) {
        return ServerResponse.ok().contentType(APPLICATION_JSON).body(userRepository.findAll(),User.class);
    }

    /**
     * 更新用户信息
     * @param request
     * @return
     */
    public Mono<ServerResponse> updateUserById(ServerRequest request) {
        Mono<User> userMono = request.bodyToMono(User.class).flatMap(user -> userRepository.save(user));
        return ServerResponse.ok().contentType(APPLICATION_JSON).body(userMono,User.class);
    }

    /**
     * 保存用户信息
     * @param request
     * @return
     */
    public Mono<ServerResponse> saveUser(ServerRequest request) {
        Mono<User> userMono = request.bodyToMono(User.class).flatMap(user -> userRepository.save(user));
        return ServerResponse.ok().contentType(APPLICATION_JSON).body(userMono,User.class);
    }

    /**
     * 删除用户信息
     * @param request
     * @return
     */
    public Mono<ServerResponse> deleteUserById(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        return ServerResponse.ok().contentType(APPLICATION_JSON).body(userRepository.deleteById(id),Void.class);
    }
}
